package com.shchuangzhi.smartguard.core;

import android.content.SharedPreferences;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.SharedPref;

/**
 * Created by j_hu on 7/17/17.
 */

public class Machine {
    private int id = -1;
    private String name;
    private MachineType machineType;
    private String hostIp;
    private static final Machine machine = new Machine();

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getRootName() {
        String rootName = getName();
        if (rootName != null && rootName.length() != 0) {
            String[] split = rootName.split("-");
            if (split.length >= 2) {
                rootName = String.format("%s-%s", split[0], split[1]);
            }
        }
        return rootName;
    }

    public MachineType getType() {
        return machineType;
    }

    public void setHostIp(String ip) {
        this.hostIp = ip;
    }

    public String getHostURL() {
        String url = SharedPref.getInstance().getLocalServiceURL();
        if (url == null || url.trim().length() == 0) {
            url = String.format("http://%s:9000", hostIp);
        }
        return url;
    }

    public void init() {
        name = SharedPref.getInstance().getTerminalName();
        machineType = SharedPref.getInstance().getMachineSwitchValue() ?
                MachineType.Gate : MachineType.Receiver;

        String[] splits = name.split("-");
        if (splits.length >= 3) {
            try {
                if (machineType == MachineType.Gate) {
                    id = Integer.parseInt(splits[2]);
                } else {
                    id = Integer.parseInt(splits[3]);
                }
            } catch(Exception e) {
                XLog.e(e);
            }
        }
    }

    public static final Machine getInstance() {
        return machine;
    }

    public enum MachineType {
        Gate,
        Receiver
    }
}
